import { Component, Vue } from 'vue-property-decorator'
import style from '../AuthorizeNew/AuthorizeNew.less'
import AuthSeal from '@/modules/authSeal'
// import SealDrawer from '@/modules/sealDrawer'
import { Action } from 'vuex-class'

@Component({})
export default class AuthorizeUpdate extends Vue {
  loading: boolean = false
  footerHeight: number = 46
  selectApp: any[] = []
  selectSeals: any[] = []
  //  drawer: boolean = false
  //  isAll: boolean = false // 当前应用是否为全部授权
  authCount: number = 0 // 已授权印章数量
  isCancel: boolean = false // 是否为取消授权

  @Action('project/authorizeManageSeal') authorizeManageSeal!: any
  @Action('project/authorizeAllManageSeal') authorizeAllManageSeal!: any
  @Action('project/queryManageSealProjectAuthorizeSealsCount')
  queryManageSealProjectAuthorizeSealsCount!: any
  @Action('project/cancelAuthorizeAllManageSeal')
  cancelAuthorizeAllManageSeal!: any
  @Action('project/cancelAuthorizeManageSeal')
  cancelAuthorizeManageSeal!: any
  protected render() {
    return (
      <div class={style.flex}>
        <div class={[[style.steps], [style.header]]} style="height:60px">
          <label>{`${this.isCancel ? '取消' : ''}`}授权对象：</label>
          {this.selectApp && this.selectApp.length > 0 && (
            <span class={style.text}>
              <span>
                <label>应用名称</label>
                <span title={this.selectApp[0].projectName}>
                  {this.selectApp[0].projectName}
                </span>
              </span>
              <span>
                <label>应用主管单位</label>
                <span title={this.selectApp[0].projectOrganizeName}>
                  {this.selectApp[0].projectOrganizeName}
                </span>
              </span>
              <span>
                <label>应用开发单位</label>
                <span title={this.selectApp[0].developerName}>
                  {this.selectApp[0].developerName}
                </span>
              </span>
            </span>
          )}
        </div>
        {this.selectApp.length > 0 && (
          <AuthSeal
            class={style.orderList}
            style={{
              top: '80px',
              height: `calc(100% - 80px - ${this.footerHeight}px)`,
            }}
            appId={(this.selectApp[0] || {}).projectId}
            isAuth={!this.isCancel}
            onSelectChange={(val: any[]) => {
              this.selectSeals = val
              this.getPaddingBottom()
            }}
            emptyText={
              this.isCancel
                ? '当前查询条件下暂无已授权印章'
                : '当前查询条件下暂无可授权印章'
            }
            selection={this.selectSeals}
            isUpdate
            onAuth={this.sealAuth}
          />
        )}
        <div class={style.pagination} ref="footer">
          <div class={style.selection}>
            <p class={style.tagName}>
              <i class="el-icon-info" />
              已选择印章
            </p>
            <div class={style.tags}>
              {this.selectSeals &&
                this.selectSeals.map((tag: any) => (
                  <el-tag
                    key={tag.id}
                    closable
                    disable-transitions={false}
                    onClose={() => this.deleteSeal(tag)}
                  >
                    {tag.sealName}
                  </el-tag>
                ))}
            </div>
          </div>

          <div class={style.operations}>
            <el-button
              type="primary"
              class={['bg-color-blue', { [style.medium]: true }]}
              onClick={() => {
                this.partAuth()
              }}
              disabled={this.loading || this.selectSeals.length === 0}
            >
              {this.isCancel ? `批量取消授权` : `批量授权`}
            </el-button>
            {/* {!this.isAll && ( */}
            <el-button
              type="primary"
              class={['bg-color-blue', { [style.medium]: true }]}
              onClick={this.allAuth}
              disabled={this.loading || this.authCount === 0}
            >
              {this.isCancel ? `全部取消授权` : `全部授权`}
            </el-button>
            {/* )} */}
            <span class={style.info}>
              当前选中<span>{this.selectSeals.length}</span>枚印章，共
              <span>{this.getOrgCount()}</span>
              个机构
            </span>
            {/* <span class={style.info}>
              已授权<span>{this.authCount}</span>枚印章
            </span>
            <el-button type="text" onClick={this.detail}>
              前往取消授权
            </el-button> */}
          </div>
        </div>
        {/* <SealDrawer
          visible={this.drawer}
          isAll={this.isAll}
          title="已选印章"
          isSelect
          project={this.selectApp[0] || {}}
          {...{
            on: {
              'update:visible': (val: boolean) => {
                this.drawer = val
              },
            },
          }}
        /> */}
      </div>
    )
  }

  getOrgCount() {
    // 获取机构数量
    return [...new Set(this.selectSeals.map(seal => seal.organizeUUID))].length
  }

  created() {}
  mounted() {
    const projectId = (this.$route.query.id as string) || ''
    const projectName = (this.$route.query.name as string) || ''
    const projectOrganizeName =
      (this.$route.query.projectOrganizeName as string) || ''
    const developerName = (this.$route.query.developerName as string) || ''
    this.isCancel = (this.$route.params.type as string) === 'cancel'
    this.selectApp = [
      { projectId, projectName, developerName, projectOrganizeName },
    ]
    this.getAuthCount()
    this.getPaddingBottom()
  }
  getAuthCount() {
    this.queryManageSealProjectAuthorizeSealsCount({
      projectId: (this.selectApp[0] || {}).projectId,
      authorize: this.isCancel,
    }).then((res: any) => {
      if (!res) return
      // this.isAll = res.all
      this.authCount = res.count
    })
  }
  // detail() {
  //   this.drawer = true
  // }

  getPaddingBottom() {
    this.$nextTick(() => {
      this.footerHeight = (
        (this.$refs.footer as any) || { offsetHeight: 46 }
      ).offsetHeight
    })
  }

  deleteApp(app: any) {
    this.selectApp = this.selectApp.filter(
      (select: any) => app.projectId !== select.projectId
    )
  }
  deleteSeal(seal: any) {
    this.selectSeals = this.selectSeals.filter(
      (select: any) => seal.id !== select.id
    )
  }

  sealAuth(row: any) {
    this.partAuth([row.sealCode])
  }

  partAuth(seals?: string[]) {
    if (this.selectApp.length === 0) {
      this.$message.warning('请选择授权应用')

      return
    }
    if ((seals || []).length === 0 && this.selectSeals.length === 0) {
      this.$message.warning(`请选择${this.isCancel ? '取消' : ''}授权印章`)

      return
    }
    const projectIds = this.selectApp.map(app => app.projectId) || []
    const sealCodes = seals || this.selectSeals.map(seal => seal.sealCode)
    this.loading = true
    const url = this.isCancel
      ? this.cancelAuthorizeManageSeal
      : this.authorizeManageSeal
    url({ projectId: projectIds[0], sealCodes })
      .then((res: any) => {
        this.loading = false
        this.$router.push({
          name: 'authorizeResult',
          query: {
            id: this.selectApp[0].projectId,
            name: this.selectApp[0].projectName,
            cancel: this.isCancel ? '1' : undefined,
          },
        })
      })
      .catch(() => {
        this.loading = false
      })
  }

  allAuth() {
    // 全部授权
    this.$confirm(
      `确认${this.isCancel ? '取消' : ''}授权当前所有印章？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnPressEscape: false,
        closeOnClickModal: false,
        customClass: 'custom-confirm',
      }
    )
      .then(() => {
        this.confirmAuth()
      })
      .catch(() => {})
  }

  confirmAuth() {
    const projectIds = this.selectApp.map(app => app.projectId) || []
    this.loading = true
    const url = this.isCancel
      ? this.cancelAuthorizeAllManageSeal
      : this.authorizeAllManageSeal
    url({ projectId: projectIds[0] })
      .then((res: any) => {
        this.loading = false
        this.$router.push({
          name: 'authorizeResult',
          query: {
            id: (this.selectApp[0] || {}).projectId,
            name: (this.selectApp[0] || {}).projectName,
            cancel: this.isCancel ? '1' : undefined,
          },
        })
      })
      .catch(() => {
        this.loading = false
      })
  }
}
